package com.jtlrm.ckd.mvp.view.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.DateFormatUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.fragment.BaseFragment;
import com.jtlrm.ckd.entity.ApkUpdateEntity;
import com.jtlrm.ckd.entity.PageEntity;
import com.jtlrm.ckd.entity.ShengHuaCheckEntity;
import com.jtlrm.ckd.entity.YingYangDetailData;
import com.jtlrm.ckd.entity.YingYangHistoryEntity;
import com.jtlrm.ckd.entity.event.YinShiUpdateMessage;
import com.jtlrm.ckd.entity.event.YingYangUpdateMessage;
import com.jtlrm.ckd.mvp.model.YinYangModel;
import com.jtlrm.ckd.mvp.view.activity.YingYangPingGuDetailActivity;
import com.jtlrm.ckd.mvp.view.adapter.YingYangPingGuAdapter;
import com.jtlrm.ckd.util.EventBusUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;

/**
 * 营养评估
 */
public class YinYangPingGuFragment extends BaseFragment {
    private static final String ARG_PARAM1 = "patientId";
    private String patientId;
    YinYangModel yinYangModel;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private int pageNum = 1;
    private int pageSize = 12;
    YingYangPingGuAdapter adapter;
    DateFormatUtil dateFormatUtil = new DateFormatUtil();

    public YinYangPingGuFragment() {
        // Required empty public constructor
    }


    public static YinYangPingGuFragment newInstance(String patientId) {
        YinYangPingGuFragment fragment = new YinYangPingGuFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, patientId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            patientId = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    protected int setContentLayout() {
        return R.layout.fragment_yin_yang_ping_gu;
    }

    @Override
    protected void initView() {
        yinYangModel = new YinYangModel();
        adapter = new YingYangPingGuAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);
        View header = LayoutInflater.from(context).inflate(R.layout.yingyang_pinggu_data_header, recyclerView, false);
        header.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<YingYangHistoryEntity> list = adapter.getData();
                for (YingYangHistoryEntity entity : list) {
                    if (entity.getBrId() == 0) {
                        // 未引用,可编辑
                        showToast("今天已经填写了记录，如需填写，请直接修改");
                        return;
                    }
                }
                YingYangPingGuDetailActivity.goDetail(context, true, patientId, null);
            }
        });
        adapter.addHeaderView(header);
        EventBusUtil.register(this);
    }

    @Override
    protected void obtainData() {

    }

    @Override
    protected void initEvent() {
        adapter.openLoadAnimation();
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                loadData();
            }
        });
        smartRefreshLayout.autoRefresh();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                YingYangHistoryEntity item = (YingYangHistoryEntity) adapter.getItem(position);
                YingYangDetailData submitData = new YingYangDetailData();
                submitData.setpHeight(item.getpHeight());
                submitData.setpWeight(item.getpWeight());
                submitData.setBim(item.getBim());
                submitData.setUpperArm(item.getUpperArm());
                submitData.setTricepsBrachii(item.getTricepsBrachii());
                submitData.setLeftGrip(item.getLeftGrip());
                submitData.setRightGrip(item.getRightGrip());
                submitData.setHighBlood(item.getHighBlood());
                submitData.setLowBlood(item.getLowBlood());
                if (item.getBrId() == 1) {
                    // 已引用,不可编辑
                    YingYangPingGuDetailActivity.goDetail(context, false, patientId, submitData);
                } else if (item.getBrId() == 2) {
                    // 已过期,不可编辑
                    YingYangPingGuDetailActivity.goDetail(context, false, patientId, submitData);
                } else if (item.getBrId() == 0) {
                    // 未引用,可编辑
                    YingYangPingGuDetailActivity.goDetail(context, false, patientId, null);
                }
            }
        });
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                YingYangHistoryEntity item = (YingYangHistoryEntity) adapter.getItem(position);
                if (item.getBrId() == 1) {
                    // 已引用,不可编辑
                } else if (item.getBrId() == 2) {
                    // 已过期,不可编辑
                } else if (item.getBrId() == 0) {
                    // 未引用,可编辑
                    showVersionDialog(item);
                }
                return false;
            }
        });
    }

    private void showVersionDialog(final YingYangHistoryEntity data) {
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.setCancelable(false);
        dialog.title("是否确认删除");
        dialog.setCanceledOnTouchOutside(false);
        //dialog.content(data.getDescription() + "");
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
                deleteYingYang(data);
            }
        });
        dialog.show();
    }

    private void deleteYingYang(YingYangHistoryEntity data) {
        showLoadingDialog("刪除中");
        yinYangModel.deleteYingYangData(patientId, new CommonObserver<Object>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(Object data) {
                dismissLoadingDialog();
                showToast("刪除成功");
                smartRefreshLayout.autoRefresh();
            }
        }, lifecycleSubject);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(YingYangUpdateMessage message) {
        if (message != null) {
            pageNum = 1;
            loadData();
        }
    }

    private void loadData() {
        yinYangModel.queryHistroy(patientId, pageNum, pageSize, new CommonObserver<PageEntity<List<YingYangHistoryEntity>>>() {
            @Override
            public void onError(int errType, String errMessage) {
                closeFrshorLoadmore();
                showToast(errMessage);
            }

            @Override
            public void onResult(PageEntity<List<YingYangHistoryEntity>> data) {
                String yuefen = "";
                try {
                    for (YingYangHistoryEntity entity : data.getItems()) {
                        String date = dateFormatUtil.getMonth(entity.getAssessmentTime()) + "";
                        entity.setYueFen(date + "月");
                        if (date.equals(yuefen)) {
                            entity.setFirst(false);
                        } else {
                            entity.setFirst(true);
                        }
                        yuefen = date;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (pageNum > 1) {
                    adapter.addData(data.getItems());
                } else {
                    adapter.replaceData(data.getItems());
                }
                closeFrshorLoadmore();
                if (data.getItems().size() < pageSize) {
                    smartRefreshLayout.setEnableLoadmore(false);
                } else {
                    smartRefreshLayout.setEnableLoadmore(true);
                }
            }
        }, lifecycleSubject);
    }


    @Override
    public void onDetach() {
        super.onDetach();

    }

    /**
     * 关闭加载更多或者刷新
     */
    private void closeFrshorLoadmore() {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadmore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }


}
